const mongoose=require('mongoose');
const News = require('../models/news.model');
const Cate = require('../models/cate.model')

exports.create=function(req,res,next){
    const kitty = new News(req.body);
    kitty.save().then(data => {
        res.json(data);
    });
}

exports.updata=function(req,res,next){
    var id = req.params.id;
    News.findByIdAndUpdate(id,{$set:req.body},{new:false})
    .then(data=>{
        res.json(data);
    })
}

exports.get=function(req,res,next){
    var id = req.params.id;
    News.findById(id)
    .then(data=>{
        res.json(data);
    })
}

exports.remove=function(req,res,next){
    var id = req.params.id;
    News.findByIdAndRemove(id)
    .then(data=>{
        res.json(data);
    })
}

exports.removes=function(req,res,next){
    var ids = req.body.ids.split(',');
    Users.remove({_id:{ $in: ids}}).then(()=>{
        res.json({"message":"删除记录成功",status:200})
    })
}

exports.list = function (req, res, next) {
    var page           = req.body.page ? req.body.page : 1;
    var rows           = req.body.rows ? req.body.rows : 5;
    var queryCondition = {}
    var arr            = []
    if (req.body.cateId && req.body.cateId.length > 0) {
        cateId = req.body.cateId
        Cate.findOne({ _id: cateId }, function (err, doc) {
            arr.push(doc._id)
            doc.getChildren(function (err, docs) {
                if (docs && docs.length > 0) {
                    for (var i = 0; i < docs.length; i++) {
                        arr.push(docs[i]._id)
                    }
                }
                queryCondition = {
                    cateId: { $in: arr },
                }
                if (req.body.title && req.body.title.length > 0) {
                    title          = req.body.title
                    queryCondition = Object.assign(queryCondition, {
                        title: new RegExp(title, 'i'),
                    })
                }

                News.paginate(queryCondition, { page: +page, limit: +rows }, function (err, result) {
                    result.rows = result.docs
                    delete result.docs
                    if(result.rows.length==0){
                        result.page = result.page-1
                    }
                    res.json(result)
                })
                
            })

        })
    } 
    else {
        // if (req.body.title && req.body.title.length > 0) {
            
        //     title          = req.body.title
        //     queryCondition = Object.assign(queryCondition, {
        //         title: new RegExp(title, 'i'),
        //     })
        // }

        News.paginate(queryCondition, { page: +page, limit: +rows }, function (err, result) {
            result.rows = result.docs
            delete result.docs
            if(result.rows.length==0){
                result.page = result.page-1
            }
            res.json(result)
        })
    }
    

}